<?php
// 应用公共文件
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Config;
use app\common\model\tang\Cost;
use app\common\model\tang\Merchant;
use app\common\model\tang\MonthElectricityDegree;
use think\facade\Cache;
use think\cache\driver\Redis;
//加载用户自定义的公共方法
if (file_exists(__DIR__ . "/../app/function.php")) {
    require __DIR__ . "/../app/function.php";
}
if (!function_exists("getBill")) {
    function getBill()
    {
        $redis = (new Redis(config('queue.connections.redis')));
        $count = $redis->llen('HFZD' . date('Ymd'));
        $redis->delete('HFZD' . date('Ymd', strtotime('-1 day')));
        if ($count == 0) {
            for ($i = 99999; $i >= 0; $i--) {
                $jh = str_pad($i, 5, "0", STR_PAD_LEFT);
                $redis->lPush('HFZD' . date('Ymd'), $jh);
            }
        }
        $time = date('Ymd', time());
        $bill = 'HFZD' . $time . $redis->lpop('HFZD' . date('Ymd'));
        return $bill;
    }
}
if (!function_exists("moneyToString")){
    //$num:金额
    function moneyToString($num)
    {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
//            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
//            } else {
//                $c = $p1 . $c;
//            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
//        dump($c);
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }

        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }
//        dump($c);
//        dump(strlen($c));dd();
        $ss = strlen($c)/6; //计算得出使用了几个大写字
        $s = substr($c2,3*$ss);
        $k = 0;
        $ii = strlen($s)/3;
//        dump($ii);
        while($k<$ii){
            $p1 = substr($s, 3 * $k, 3);
            $c = '零'.$p1 .$c;
            $k++;
        }
//       $c = strtr($c,'零','〇');
        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元";
        } else {
            return $c ;
        }
    }
}
if (!function_exists('__')) {
    /**
     * @param $name
     * @param array $vars
     * @param string $lang
     * @return mixed
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:获取语言变量值
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\facade\Lang::get($name, $vars, $lang);
    }
}

if (! function_exists('upload_file')) {
    /**
     * @param null $file
     * @param string $name
     * @param string $path
     * @param string $validate
     * @param string $url
     * @return bool|string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:上传文件.
     */
    function upload_file($file = null, $name = 'local', $path = '', $validate = '', $url = '/')
    {
        //文件
        if (! $file) {
            return false;
        }
        //上传配置
        $config_name = 'filesystem.disks.'.$name;
        $filesystem = config($config_name);
        if (! $filesystem) {
            return false;
        }
        //上传文件
        if ($validate) {
            validate(['file' => $validate])->check(['file' => $file]);
        }
        $savename = \think\facade\Filesystem::disk($name)->putFile($path, $file, function ($file) {
            //重命名
            return date('Ymd').'/'.md5((string) microtime(true));
        });
        if(empty($url)){
            $url = '/';
        }
        $savename = $url.$savename;

        return $savename;
    }
}


if (! function_exists('parseName')) {
    /**
     * @param $name
     * @param int $type
     * @param bool $ucfirst
     * @return string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:
     */
    function parseName($name, $type = 0, $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);

            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }
        return strtolower(trim(preg_replace('/[A-Z]/', '_\\0', $name), '_'));
    }
}

if (!function_exists('create_min_code')) {
    /**
     * @param $param
     * @param bool $domain
     * @return string
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:生成小程序二维码（小程序必须发布）
     */
    function create_min_code($param,$domain=false)
    {
        return \app\common\traits\QrcodeMin::min_qrcode($param,$domain);
    }
}



if (!function_exists("makeToken")){
    /**
     * @return string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @name: makeToken
     * @describe:生成一个不会重复的字符串
     */
    function makeToken()
    {
        $str = md5(uniqid(md5(microtime(true)), true)); //
        $str = sha1($str); //加密
        return $str;
    }
}



if (!function_exists('create_qrcode')) {
    /**
     * @param $text //文本
     * @param int $ize //大小
     * @param bool $domain //是否返回当前域名
     * @return string
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:生成普通二维码
     */
    function create_qrcode($text,$ize=105,$domain=false){
        return \app\common\service\QrcodeSrvice::make_qrcode($text,$ize,$domain);
    }
}

if(!function_exists("curl_get")){
    /**
     * @param $url
     * @param array $data
     * @return mixed
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:curl请求(get)
     */
    function curl_get($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
}

if (!function_exists('array_merge_multiple')) {

    /**
     * @param $array1
     * @param $array2
     * @return array
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:多维数组合并
     */
    function array_merge_multiple($array1, $array2)
    {
        $merge = $array1 + $array2;
        $data = [];
        foreach ($merge as $key => $val) {
            if (isset($array1[$key])
                && is_array($array1[$key])
                && isset($array2[$key])
                && is_array($array2[$key])
            ) {
                $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
            } else {
                $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
            }
        }
        return $data;
    }
}



if (!function_exists('curl_post')) {

    /**
     * @param $url
     * @param array $data
     * @return mixed
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:curl请求(POST)
     */
    function curl_post($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
if (!function_exists('sysconfig')) {

    /**
     * @param $group //分组名
     * @param null $name //配置名
     * @return array|bool|float|mixed|string|null
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:获取系统配置信息
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SysConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SysConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}


if (!function_exists('exception')) {
    /**
     * @param $msg
     * @param int $code
     * @param string $exception
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/29 0029
     * @describe:抛出异常处理
     */
    function exception($msg, $code = 0, $exception = '')
    {
        $e = $exception ?: '\think\Exception';
        throw new $e($msg, $code);
    }
}

if (!function_exists('password')) {
    /**
     * @param $value
     * @return false|string|null
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:密码加密算法
     */
    function password($value)
    {
        $value = sha1('jrk_') . md5($value) . md5('_encrypt') . sha1($value);
        return password_hash($value, PASSWORD_DEFAULT);
    }
}


if (!function_exists('password_very')) {
    /**
     * @param $value //密码
     * @param $pass //数据库存的 hash值
     * @return bool
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:验证密码
     */
    function password_very($value, $pass)
    {
        $value = sha1('jrk_') . md5($value) . md5('_encrypt') . sha1($value);
        return password_verify($value, $pass);
    }
}


if (!function_exists('array_format_key')) {
    /**
     * @param $array
     * @param $key
     * @return array
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:二位数组重新组合数据
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }
}


if (!function_exists('node')) {
    /**
     * @param null $node
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe: 按钮权限认证 {:node('Login/index')} //写在按钮的class里面
     */
    function node($node = null)
    {
        $k = \app\admin\model\AuthRule::auth_verify($node);
        if ($k == true) {
            $str = "";
        } else {
            $str = "node_hide";
        }
        echo $str;
    }

}


if (!function_exists('make_path')) {

    /**
     * @param $path
     * @param int $type
     * @param bool $force
     * @return string
     * @throws Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:上传路径转化,默认路径
     */
    function make_path($path, int $type = 2, bool $force = false)
    {
        $path = DS . ltrim(rtrim($path));
        switch ($type) {
            case 1:
                $path .= DS . date('Y');
                break;
            case 2:
                $path .= DS . date('Y') . DS . date('m');
                break;
            case 3:
                $path .= DS . date('Y') . DS . date('m') . DS . date('d');
                break;
        }
        try {
            if (is_dir(app()->getRootPath() . 'public' . DS . 'uploads' . $path) == true || mkdir(app()->getRootPath() . 'public' . DS . 'uploads' . $path, 0777, true) == true) {
                return trim(str_replace(DS, '/', $path), '.');
            } else return '';
        } catch (\Exception $e) {
            if ($force)
                throw new \Exception($e->getMessage());
            return '无法创建文件夹，请检查您的上传目录权限：' . app()->getRootPath() . 'public' . DS . 'uploads' . DS . 'attach' . DS;
        }

    }
}


if (!function_exists('filterEmoji')) {
    /**
     * @param $str
     * @return string|string[]|null
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/6/28 0028
     * @describe:过滤掉emoji表情
     */
    function filterEmoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}

if (!function_exists('get_this_class_methods')) {
    /**
     * @param $class
     * @param array $unarray
     * @return array
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/29 0029
     * @describe:
     */
    function get_this_class_methods($class, $unarray = [])
    {
        $arrayall = get_class_methods($class);
        if ($parent_class = get_parent_class($class)) {
            $arrayparent = get_class_methods($parent_class);
            $arraynow = array_diff($arrayall, $arrayparent);//去除父级的
        } else {
            $arraynow = $arrayall;
        }
        return array_diff($arraynow, $unarray);//去除无用的
    }
}




if (!function_exists('build_ueditor')) {
    /**
     * @param array $params
     * @return string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @name: build_ueditor
     * @describe:百度编辑器内容
     */
    function build_ueditor($params = array())
    {
        $name = isset($params['name']) ? $params['name'] : null;
        $theme = isset($params['theme']) ? $params['theme'] : 'normal';
        $content = isset($params['content']) ? $params['content'] : null;
        $h = isset($params['h']) ? $params['h'] : 350;
        /* 指定使用哪种主题 */
        $themes = array(
            'normal' => "[   
           'fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'drafts', 'help'
       ]", 'simple' => " ['fullscreen', 'source', 'undo', 'redo', 'bold']",
        );
        switch ($theme) {
            case 'simple':
                $theme_config = $themes['simple'];
                break;
            case 'normal':
                $theme_config = $themes['normal'];
                break;
            default:
                $theme_config = $themes['normal'];
                break;
        }
        /* 配置界面语言 */
        switch ('zh-cn') {
            case 'zh-cn':
                $lang = '/plugs/ueditor/lang/zh-cn/zh-cn.js';
                break;
            case 'en-us':
                $lang =  '/plugs/ueditor/lang/en/en.js';
                break;
            default:
                $lang = '/plugs/ueditor/lang/zh-cn/zh-cn.js';
                break;
        }
        $include_js = '<script type="text/javascript" charset="utf-8" src="/plugs/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/plugs/ueditor/ueditor.all.min.js""> </script><script type="text/javascript" charset="utf-8" src="' . $lang . '"></script>';
        $content = json_encode($content);
        $str = <<<EOT
$include_js
<script type="text/javascript">
var ue = UE.getEditor('{$name}',{
    toolbars:[{$theme_config}],
    autoHeightEnabled:false,
    initialFrameHeight:{$h},
        });
    if($content){
ue.ready(function() {
       this.setContent($content);	
})
   }
</script>
EOT;
        return $str;
    }
}


if(!function_exists("is_email")){
    function is_email($user_email)
    {
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
            if (preg_match($chars, $user_email)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}


if(!function_exists("send_email")){
    /**
     * @param $to
     * @param string $subject 邮件标题
     * @param string $content 邮件内容(html模板渲染后的内容)
     * @author: Hhy <jackhhy520@qq.com>
     * @describe: 发送邮件
     */
    function send_email($to, $subject = '', $content = ''){
        $mail = new PHPMailer\PHPMailer\PHPMailer();
        $config =sysconfig("smtp");//获取配置
        $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        //调试输出格式
        //$mail->Debugoutput = 'html';
        //smtp服务器
        $mail->Host = $config['smtp_server'];
        //端口 - likely to be 25, 465 or 587
        $mail->Port = $config['smtp_port'];

        if ($mail->Port == '465') {
            $mail->SMTPSecure = 'ssl';
        }// 使用安全协议
        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;
        //发送邮箱
        $mail->Username = $config['smtp_user'];
        //密码
        $mail->Password = $config['smtp_pwd'];
        //Set who the message is to be sent from
        $mail->setFrom($config['smtp_user'], $config['email_id']);
        //回复地址
        //$mail->addReplyTo('replyto@example.com', 'First Last');
        //接收邮件方
        if (is_array($to)) {
            foreach ($to as $v) {
                if(is_email($v)){
                    $mail->addAddress($v);
                }
            }
        } else {
            if(is_email($to)){
                $mail->addAddress($to);
            }
        }
        $mail->isHTML(true);// send as HTML
        //标题
        $mail->Subject = $subject;
        //HTML内容转换
        $mail->msgHTML($content);
        return $mail->send();
    }
}



if (!function_exists('add_log')){
    /**
     * @param $param
     * @param string $file 文件夹
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:
     */
     function writeLog($param,$file=''){
         $filename=date("Y_m_d",time());
         if (empty($root)) {
             $myfile =$filename.".txt";
         }else{
             $f=app()->getRootPath().'Logs/'.$file."/";
             if (!is_dir($f)){
                 @mkdir($f,0777,true);
             }
             $myfile=app()->getRootPath().'Logs/'.$file."/".$filename.".txt";
         }
         if (is_array($param)){
             $param=json_encode($param,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE);
         }
         @file_put_contents(
             $myfile,
             "执行日期："."\r\n".date('Y-m-d H:i:s', time()) . ' ' . "\n" . $param . "\r\n",
             FILE_APPEND
         );
    }

    /**
     * 公区计算分摊
     */
    function getFen($v,$param){
        $fm = bcmul(1, $v['fengPower'], 4);//峰电量*倍率 = 峰实际用量
        $gm = bcmul(1,$v['guPower'], 2);
        $pm = bcmul(1, $v['pingPower'], 2);
        $fmoney = bcmul($fm, isset($param['fmoney'])?$param['fmoney']:$param['fMoney'], 2);//峰电价
        $gmoney = bcmul($gm, isset($param['gmoney'])?$param['gmoney']:$param['gMoney'], 2);//谷电价
        $pmoney = bcmul($pm, isset($param['pmoney'])?$param['pmoney']:$param['pMoney'], 2);//平电价
        $allMoney=bcadd(bcadd($fmoney, $gmoney, 2), $pmoney, 2);//4位截取,为了对账
        return $allMoney;
    }
    /**
     * 峰谷平电量进行计算
     */
    function rate($v,$param){
        $fstr = bcsub($v['fengEnd'], $v['fengStart'], 4);
        $gstr = bcsub($v['guEnd'], $v['guStart'], 4);
        $pstr = bcsub($v['pingEnd'], $v['pingStart'], 4);
        $fm = bcmul($v['rate'], $fstr, 4);//峰电量*倍率 = 峰实际用量
        $gm = bcmul($v['rate'],$gstr, 4);
        $pm = bcmul($v['rate'], $pstr, 4);
        if($param['add_price']>1){
            $param['fmoney'] =bcmul( $param['fmoney'],(1+$param['add_price']/100),4);
            $param['gmoney'] = bcmul( $param['gmoney'],(1+$param['add_price']/100),4);;
            $param['pmoney'] =  bcmul($param['pmoney'],(1+$param['add_price']/100),4);;
        }

        //分摊电价 = 峰谷平*分摊电价
        $fmoney = bcmul($fm, isset($param['fmoney'])?$param['fmoney']:$param['fMoney'], 2);//峰电价
        $gmoney = bcmul($gm, isset($param['gmoney'])?$param['gmoney']:$param['gMoney'], 2);//谷电价
        $pmoney = bcmul($pm, isset($param['pmoney'])?$param['pmoney']:$param['pMoney'], 2);//平电价
        $jfmoney = bcmul($fm, isset($param['fmoney'])?$param['fmoney']:$param['fMoney'], 2);//峰电价 4位截取
        $jgmoney = bcmul($gm, isset($param['gmoney'])?$param['gmoney']:$param['gMoney'], 2);//谷电价 4
        $jpmoney = bcmul($pm, isset($param['pmoney'])?$param['pmoney']:$param['pMoney'], 2);//平电价 4
        $subtotal = bcadd(bcadd($fmoney,$gmoney,2),$pmoney,2);//分摊电价
        $tmoney = bcmul(bcadd(bcadd($fm, $gm, 2), $pm, 2), isset($param['tmoney'])?$param['tmoney']:$param['tMoney'], 2);
        $jtmoney = bcmul(bcadd(bcadd($fm, $gm, 2), $pm, 2), isset($param['tmoney'])?$param['tmoney']:$param['tMoney'], 2);
        $allElectricity=  bcadd(bcadd($fm, $gm, 2), $pm, 2);
        $jiMoney=bcadd(bcadd(bcadd($jfmoney, $jgmoney, 2), $jpmoney, 2), $jtmoney, 2);//4位截取,为了对账
        $allMoney=bcadd(bcadd(bcadd($fmoney, $gmoney, 2), $pmoney, 2), $tmoney, 2);//4位截取,为了对账
        $data['fele'] = $fm; //总电量
        $data['gele'] = $gm;; //总电量
        $data['pele'] = $pm;; //总电量
        $data['allElectricity'] = $allElectricity;  //总电量
        $data['jiMoney'] = $jiMoney;//总价格  4位小数
        $data['allMoney'] = $allMoney;//保留两位小数的价格 4舍五入
        $data['fMoney'] = $fmoney;;//峰用电量  2位
        $data['gMoney'] = $gmoney;;//谷用电量  2位
        $data['pMoney'] = $pmoney;;//平用电量  2位
        $data['tMoney'] = $tmoney;;//平用电量  2位
        $data['subtotal'] = $subtotal;;//平用电量  4位
        return $data;
    }
    function getMerchant(){
        $merchant_list =\app\common\model\tang\Merchant::field('id,merchant_sn,name,company,username,code,biz_state,positions_code')->select();
        foreach ($merchant_list as $k=>$v){
            if($v['biz_state']=='stopped'){
                $v['biz_state'] = '已停止';
            }
            if($v['biz_state']=='effect'){
                $v['biz_state'] = '进行中';
            }
            if($v['biz_state']=='ineffect'){
                $v['biz_state'] = '待生效';
            }
        }
        return $merchant_list;
    }
    /**
     * 水费账单
     */
    function waterBill($v,$price){
        $waterUse= bcsub($v['end'], $v['start'], 2);
//        $beele = bcmul($waterUse, $v['rate'], 2);
        $beele = $waterUse;
        $allMoney =bcmul($beele, $price, 2);
        $jiMoney =bcmul($beele, $price, 2);
        $data['jiMoney'] = $jiMoney;
        $data['allMoney'] = $allMoney;
        $data['water'] = $beele;
        return $data;
    }
    function mergeImage($costId){

        $model = new Cost();
        $info = $model->with(['costType', 'merchants'])->where('pay_status', 1)->find($costId);
        if(is_file('uploads/cost/'.$info['id'].'_'.$info['order_sn'].'.png')){
            return 'uploads/cost/'.$info['id'].'_'.$info['order_sn'].'.png';
        }
        $time = explode('-', $info['pay_time']);
        $date = explode(' ', $time[2]);
        $result['time'] = $time[0] . ' 年 ' . $time[1] . ' 月 ' . $date[0] . ' 日';
        $result['No'] = $info['bill_no'];
        $result['shoujufang'] = $info['merchants']['company'];
        $result['amount'] = $info->all_amount / 100;
        $result['zje'] = moneyToString($result['amount']);
        $result['liushui'] = $info['order_sn'];
        $result['cost_sn'] = $info['costType']['cost_sn'];
        $result['positions_code'] = $info['merchants']['positions_code'];
        $result['brand'] = $info['merchants']['name'];
        $result['tenant_name'] = $info['merchants']['tenant_name'];
        $result['code'] = $info['merchants']['code'];
        $result['pay_user'] = $info['merchants']['tenant_name'];
        $result['title'] = $info['costType']['cost_name'].'('.date('Y-m-d',$info['start_time']).'~'.date('Y-m-d',$info['end_time']).')';
        if ($info['subject_id'] == 3) {
            $result['pay_way'] = '转账';
        } elseif($info['subject_id']==1) {
            $result['pay_way'] = '微信';
        }else{
            $result['pay_way'] = '余额';
        }
        header('content-type:image/jpeg');
        $font =  app()->getRootPath() . 'public/cret/FangZhengHeiTiJianTi-1.ttf';
        $im = imagecreatetruecolor(1720,1080);
        $red = imagecolorallocate($im, 255,255,255);
        $fontcolor = imagecolorallocate($im,34,34,34);
        imagefilledrectangle($im,0,0, 1720, 1080,$red);
        imagettftext($im,24,0,40,100,$fontcolor,$font,'收款');
        imagettftext($im,24,0,1200,70,$fontcolor,$font,'开具时间:'.$result['time']);
        imagettftext($im,24,0,1200,110,$fontcolor,$font,'收据编号:'.$result['No']);
        imagettftext($im,24,0,40,210,$fontcolor,$font,'收据方:'.$result['shoujufang']);
        imagettftext($im,24,0,40,310,$fontcolor,$font,'合计金额(大写):'.$result['zje']);
        imagettftext($im,24,0,880,310,$fontcolor,$font,'合计金额(小写):'.$result['amount']);
        imagettftext($im,24,0,40,410,$fontcolor,$font,'支付流水号:'.$result['liushui']);
        imagettftext($im,24,0,880,410,$fontcolor,$font,'费用项编号:'.$result['cost_sn']);
        imagettftext($im,24,0,40,510,$fontcolor,$font,'铺位编号:'.$result['positions_code']);
        imagettftext($im,24,0,880,510,$fontcolor,$font,'签约品牌:'.$result['brand']);
        $text_color = imagecolorallocate($im, 255, 0, 0);
        imageline($im, 30, 150, 1660, 150, $text_color);
        imageline($im, 30, 250, 1660, 250, $text_color);
        imageline($im, 30, 350, 1660, 350, $text_color);
        imageline($im, 30, 450, 1660, 450, $text_color);
        imageline($im, 30, 550, 1660, 550, $text_color);
        imageline($im, 30, 650, 1660, 650, $text_color);
        imageline($im, 30, 750, 1660, 750, $text_color);
        imageline($im, 30, 850, 1660, 850, $text_color);
        imageline($im, 30, 960, 1660, 960, $text_color);
        imageline($im, 30, 150, 30, 960, $text_color);
        imageline($im, 860, 150, 860, 850, $text_color);
        imageline($im, 1660, 150, 1660, 960, $text_color);
        imagettftext($im,24,0,40,610,$fontcolor,$font,'合同签约方:'.$result['tenant_name']);
        imagettftext($im,24,0,880,610,$fontcolor,$font,'合同编号:'.$result['code']);
        imagettftext($im,24,0,40,710,$fontcolor,$font,'实际付款方:'.$result['pay_user']);
        imagettftext($im,24,0,880,710,$fontcolor,$font,'收款方式:'.$result['pay_way']);
        imagettftext($im,24,0,40,810,$fontcolor,$font,'收款事由:'.$result['title']);
        imagettftext($im,24,0,40,890,$fontcolor,$font,'备注:该收据不作为退款依据保证金/押金退款以合同约定、实际结算的余额为准，合同到期、变更或终止后该');
        imagettftext($im,24,0,40,930,$fontcolor,$font,'收据作废');
        $image = 'uploads/cost/'.$info['id'].'_'.$info['order_sn'].'.jpg';
        imagejpeg($im,$image);
        imagedestroy($im);
// 创建一张空白底图
        $baseImage = imagecreatetruecolor(1720, 1080);
//        $red = imagecolorallocate($baseImage, 255,255,255);
//        imagefilledrectangle($baseImage,0,0, 800, 500,$red);
// 读取要合成的两张图片
        $image1 = imagecreatefromjpeg($image);
        $image2 = imagecreatefrompng("../zhangzi.png");
// 获取两张图片的宽高
        $image1Width = imagesx($image1);
        $image1Height = imagesy($image1);

        $image2Width = imagesx($image2);
        $image2Height = imagesy($image2);
// 将图片1复制到底图上
        imagecopy($baseImage, $image1, 0, 0, 0, 0, $image1Width, $image1Height);

// 将图片2复制到底图上
        imagecopy($baseImage, $image2, 1200, 700, 0, 0, $image2Width, $image2Height);

// 保存合成后的图片
        imagejpeg($baseImage, 'uploads/cost/'.$info['id'].'_'.$info['order_sn'].".png");

// 释放内存
        imagedestroy($baseImage);
        imagedestroy($image1);
        imagedestroy($image2);
        var_dump($image);
        unlink($image);
        return 1;
    }
    function getbalance($balance_id){
        $model = new BalanceLog();
        $info = $model->with(['merchantInfo'])->where('status', 1)->find($balance_id);
        if(is_file('uploads/charge/'.$info['id'].'_'.$info['mobile'].'.png')){
            return 'uploads/charge/'.$info['id'].'_'.$info['mobile'].'.png';
        }
        if(empty($info['transaction_id'])){
            $orderSn =  OrderSn();
        }else{
            $orderSn = $info['transaction_id'];
        }
        if(!empty($info['charge_time'])){
            $info['create_time'] == date('Y-m-d H:i',$info['charge_time']);
        }
        if(!empty($info['bill_no'])){
            $No = $info['bill_no'];
            $model->update(['order_sn'=>$orderSn,'transaction_id'=>$orderSn],['id'=>$info['id']]);
        }else{
            $No = 'CZMX'.date('Ymd', strtotime($info['create_time'])).rand(10000,99999);
            $model->update(['order_sn'=>$orderSn,'transaction_id'=>$orderSn,'bill_no'=>$No],['id'=>$info['id']]);
        }

        $time = explode('-',$info['create_time']);
        $date = explode(' ', $time[2]);
        $result['time'] = $time[0] . ' 年 ' . $time[1] . ' 月 ' . $date[0] . ' 日';
        $result['No'] = $No;
        $result['shoujufang'] = $info['merchantInfo']['company'];
        $result['amount'] = $info->amount / 100;
        $result['zje'] = moneyToString($result['amount']);
        $result['liushui'] =$orderSn;
        $result['cost_sn'] = '2205.27';
        $result['positions_code'] = $info['merchantInfo']['positions_code'];
        $result['brand'] = $info['merchantInfo']['name'];
        $result['tenant_name'] = $info['merchantInfo']['tenant_name'];
        $result['code'] = $info['merchantInfo']['code'];
        $result['pay_user'] = $info['merchantInfo']['tenant_name'];
        if ($info['type'] == 1) {
            $result['pay_way'] = '微信';
        } elseif($info['type']==2) {
            $result['pay_way'] = '转账';
        }else{
            $result['pay_way'] = '余额缴费';
        }
        header('content-type:image/jpeg');
        $font =  app()->getRootPath() . 'public/cret/FangZhengHeiTiJianTi-1.ttf';
        $im = imagecreatetruecolor(1720,1080);
        $red = imagecolorallocate($im, 255,255,255);
        $fontcolor = imagecolorallocate($im,34,34,34);
        imagefilledrectangle($im,0,0, 1720, 1080,$red);
        imagettftext($im,24,0,40,100,$fontcolor,$font,'充值记录证明');
        imagettftext($im,24,0,1200,70,$fontcolor,$font,'开具时间:'.$result['time']);
        imagettftext($im,24,0,1200,110,$fontcolor,$font,'收据编号:'.$result['No']);
        imagettftext($im,24,0,40,210,$fontcolor,$font,'单据方:'.$result['shoujufang']);
        imagettftext($im,24,0,40,310,$fontcolor,$font,'合计金额(大写):'.$result['zje']);
        imagettftext($im,24,0,880,310,$fontcolor,$font,'合计金额(小写):'.$result['amount']);
        imagettftext($im,24,0,40,410,$fontcolor,$font,'支付流水号:'.$result['liushui']);
        imagettftext($im,24,0,880,410,$fontcolor,$font,'费用项编号:'.$result['cost_sn']);
        imagettftext($im,24,0,40,510,$fontcolor,$font,'铺位编号:'.$result['positions_code']);
        imagettftext($im,24,0,880,510,$fontcolor,$font,'签约品牌:'.$result['brand']);
        $text_color = imagecolorallocate($im, 255, 0, 0);
        imageline($im, 30, 150, 1660, 150, $text_color);
        imageline($im, 30, 250, 1660, 250, $text_color);
        imageline($im, 30, 350, 1660, 350, $text_color);
        imageline($im, 30, 450, 1660, 450, $text_color);
        imageline($im, 30, 550, 1660, 550, $text_color);
        imageline($im, 30, 650, 1660, 650, $text_color);
        imageline($im, 30, 750, 1660, 750, $text_color);
        imageline($im, 30, 850, 1660, 850, $text_color);
        imageline($im, 30, 960, 1660, 960, $text_color);
        imageline($im, 30, 150, 30, 960, $text_color);
        imageline($im, 860, 150, 860, 850, $text_color);
        imageline($im, 1660, 150, 1660, 960, $text_color);
        imagettftext($im,24,0,40,610,$fontcolor,$font,'合同签约方:'.$result['tenant_name']);
        imagettftext($im,24,0,880,610,$fontcolor,$font,'合同编号:'.$result['code']);
        imagettftext($im,24,0,40,710,$fontcolor,$font,'实际付款方:'.$result['pay_user']);
        imagettftext($im,24,0,880,710,$fontcolor,$font,'收款方式:'.$result['pay_way']);
        imagettftext($im,24,0,40,810,$fontcolor,$font,'充值事项:通用预存(可用于各类账单缴费)');
        imagettftext($im,24,0,880,810,$fontcolor,$font,$info['remark']);
        imagettftext($im,24,0,40,890,$fontcolor,$font,'备注:本单据为充值记录证明，收据或发票以月度实际结算账单为准');
        $image = 'uploads/charge/'.$info['id'].'_'.$info['mobile'].'.jpg';
        imagejpeg($im,$image);
        imagedestroy($im);
// 创建一张空白底图
        $baseImage = imagecreatetruecolor(1720, 1080);
//        $red = imagecolorallocate($baseImage, 255,255,255);
//        imagefilledrectangle($baseImage,0,0, 800, 500,$red);
// 读取要合成的两张图片
        $image1 = imagecreatefromjpeg($image);
        $image2 = imagecreatefrompng("../zhangzi.png");
// 获取两张图片的宽高
        $image1Width = imagesx($image1);
        $image1Height = imagesy($image1);

        $image2Width = imagesx($image2);
        $image2Height = imagesy($image2);
// 将图片1复制到底图上
        imagecopy($baseImage, $image1, 0, 0, 0, 0, $image1Width, $image1Height);

// 将图片2复制到底图上
        imagecopy($baseImage, $image2, 1200, 700, 0, 0, $image2Width, $image2Height);

// 保存合成后的图片
        imagejpeg($baseImage, 'uploads/charge/'.$info['id'].'_'.$info['mobile'].".png");

// 释放内存
        imagedestroy($baseImage);
        imagedestroy($image1);
        imagedestroy($image2);
        var_dump($image);
        unlink($image);
        return 1;
    }
    /**
     * 手抄表电量计算
     */
    function handWritten($v,$price){
        $ele = bcsub($v['zongEnd'], $v['zongStart'], 6);
        $allElectricity = bcmul($ele, $v['rate'], 6);//倍率之后的电量
        $allMoney = bcmul($allElectricity,$price,6);
        $jiMoney = bcmul($allElectricity,$price,6);
        $data['jiMoney'] = $jiMoney;//总价格
        $data['allElectricity'] = $allElectricity; //总电量
        $data['allMoney'] = $allMoney;//保留两位小数的价格 4舍五入
        return $data;
    }
    function upMerchantAuto($id){
        $start_balance = (new Merchant())->where('id',$id)->value('start_balance');
        $frozen_balance = (new Merchant())->where('id',$id)->value('frozen_balance');
        $change = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>1,'edit'=>1,'status'=>1])->sum('amount');
        $zhuan = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>1])->sum('amount');
        $chu = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>2])->sum('amount');
        $balance_pay = (new BalanceLog())->where(['merchant_id'=>$id,'status'=>1,'type'=>3])->sum('amount');
        $cost = (new Cost())->where(['merchant_id'=>$id,'pay_status'=>1])->whereNotNull('pointId')->whereIn('cost_type_id',[45,46])->sum('all_amount');
        (new Merchant())->update([
//            'balance'=>bcsub(bcsub(bcsub(bcadd(bcadd(bcadd($start_balance,$change),$frozen_balance),$zhuan),-$chu),$cost),$money),
            'balance'=>bcsub(bcsub(bcsub(bcsub(bcadd(bcadd($start_balance,$change),$zhuan),-$chu),$cost),$frozen_balance),$balance_pay)
        ],[
            'id'=>$id
        ]);
    }
    /**
     * 更新商户余额
     */
    function upMerchantBalance($id,$money){
        $start_balance = (new Merchant())->where('id',$id)->value('start_balance');
        $frozen_balance = (new Merchant())->where('id',$id)->value('frozen_balance');
        $change = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>1,'edit'=>1,'status'=>1])->sum('amount');
        $zhuan = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>1])->sum('amount');
        $chu = (new BalanceLog())->where(['merchant_id'=>$id,'is_top_up'=>4,'edit'=>2])->sum('amount');
        $cost = (new Cost())->where(['merchant_id'=>$id,'pay_status'=>1])->whereNotNull('pointId')->whereIn('cost_type_id',[45,46])->sum('all_amount');
        $balance_pay = (new BalanceLog())->where(['merchant_id'=>$id,'status'=>1,'type'=>3])->sum('amount');

        if($money>=$frozen_balance){
            $forzen_money = 0;
        }else{
            $forzen_money = bcsub($frozen_balance,$money);
        }
        (new Merchant())->update([
//            'balance'=>bcsub(bcsub(bcsub(bcadd(bcadd(bcadd($start_balance,$change),$frozen_balance),$zhuan),-$chu),$cost),$money),
            'balance'=>bcsub(bcsub(bcsub(bcadd(bcadd(bcadd($start_balance,$change),$zhuan),-$chu),$cost),$money),$balance_pay),
            'frozen_balance'=>$forzen_money
        ],[
            'id'=>$id
        ]);
    }
    /**
     * 费率用电查看账单
     */
    function rateElectricity($list){
//        dd($list);
        $info = MonthElectricityDegree::alias('m')
            ->leftjoin('tang_watch_maintain w', 'm.pointId=w.pointId')
            ->leftjoin('tang_merchant t', 't.id=w.merchant_id')
            ->leftjoin('tang_cost c','c.settlement_time=m.dataTime')
            ->where([
                'c.settlement_time'=>$list['settlement_time'],
                'c.pointId'=>$list['pointId'],
                'c.merchant_id'=>$list['merchant_id'],
                'm.dataTime' => $list['settlement_time'],
                'm.merchant_id' => $list['merchant_id'],
                'm.pointId'=>$list['pointId'],
            ])
            ->field('m.*,t.name,t.code,t.company,c.all_amount,c.fuwu_money,c.electric_money')
            ->select();
        foreach ($info as $key => $val) {
            $info[$key]['month'] = $list['settlement_time'];
            $result = rate($val,$val);
            $info[$key]['fmoney'] =sprintf('%01.2f', $result['fMoney']);// $result['fMoney'];
            $info[$key]['fengPower'] = $val['fengPower'];
            $info[$key]['guPower'] = $val['guPower'];
            $info[$key]['pingPower'] = $val['pingPower'];
            $info[$key]['fengStart'] = $val['fengStart'];
            $info[$key]['fengEnd'] = $val['fengEnd'];
            $info[$key]['guStart'] = $val['guStart'];
            $info[$key]['guEnd'] = $val['guEnd'];
            $info[$key]['pingStart'] = $val['pingStart'];
            $info[$key]['pingEnd'] = $val['pingEnd'];
            $info[$key]['rate'] = $val['rate'];
            $info[$key]['gmoney'] =sprintf('%01.2f', $result['gMoney']); //$result['gMoney'];
            $info[$key]['pmoney'] =  sprintf('%01.2f', $result['pMoney']); //$result['pMoney'];
            $info[$key]['fele'] =sprintf('%01.2f', $result['fele']); // $result['fele'];
            $info[$key]['gele'] =sprintf('%01.2f', $result['gele']); // $result['gele'];
            $info[$key]['pele'] =sprintf('%01.2f', $result['pele']); // $result['pele'];
            $info[$key]['electricity'] = $result['allElectricity'];
            $info[$key]['tmoney'] =sprintf('%01.2f',$result['tMoney']);// $result['tMoney'];
//            $info[$key]['money'] =sprintf('%01.2f',$result['allMoney']);// $result['allMoney'];
//            $info[$key]['subtotal'] =sprintf('%01.2f',$result['subtotal']);// $result['subtotal'];
            $info[$key]['money'] =$val['all_amount']/100;// $result['allMoney'];
            $info[$key]['subtotal'] =$val['electric_money']/100;// $result['subtotal'];
            $all =bcadd(bcadd($result['fMoney'],$result['gMoney'],2),$result['pMoney'],2);
            $info[$key]['jiaji'] =bcsub($val['electric_money']/100,$all,2);// $result['subtotal'];
        }
        $newArray = $info;
//        foreach ($info as $value) {
//            if (empty($newArray[$value['id']])) {
//                $newArray[$value['id']] = $value;
//            } else {
//                $money = bcadd($newArray[$value['id']]['money'], $value['money'], 4);
//                $electricity = bcadd($newArray[$value['id']]['electricity'], $value['electricity'], 4);
//                $subtotal = bcadd($newArray[$value['id']]['subtotal'], $value['subtotal'], 4);
//                $newArray[$value['id']]['money'] = $money;
//                $newArray[$value['id']]['electricity'] = $electricity;
//                $newArray[$value['id']]['subtotal'] = $subtotal;
//                $newArray[$value['id']]['fmoney'] = bcadd($newArray[$value['id']]['fmoney'], $value['fmoney'], 4);
//                $newArray[$value['id']]['gmoney'] = bcadd($newArray[$value['id']]['gmoney'], $value['gmoney'], 4);
//                $newArray[$value['id']]['pmoney'] = bcadd($newArray[$value['id']]['pmoney'], $value['pmoney'], 4);
//                $newArray[$value['id']]['fele'] = bcadd($newArray[$value['id']]['fele'], $value['fele'], 4);
//                $newArray[$value['id']]['gele'] = bcadd($newArray[$value['id']]['gele'], $value['gele'], 4);
//                $newArray[$value['id']]['pele'] = bcadd($newArray[$value['id']]['pele'], $value['pele'], 4);
//                $newArray[$value['id']]['tmoney'] = bcadd($newArray[$value['id']]['tmoney'], $value['tmoney'], 4);
//            }
//        }
//        foreach ($newArray as $kk=>$vv){
//            $newArray[$kk]['money'] = sprintf('%01.2f',$vv['money']);
//            $newArray[$kk]['electricity'] = sprintf('%01.2f',$vv['electricity']);
//            $newArray[$kk]['subtotal'] = sprintf('%01.2f',$vv['subtotal']);
//            $newArray[$kk]['fmoney'] = sprintf('%01.4f',$vv['fmoney']);
//            $newArray[$kk]['gmoney'] =sprintf('%01.4f',$vv['gmoney']);
//            $newArray[$kk]['pmoney'] = sprintf('%01.4f',$vv['pmoney']);
//            $newArray[$kk]['fele'] = sprintf('%01.2f',$vv['fele']);
//            $newArray[$kk]['gele'] = sprintf('%01.2f',$vv['gele']);
//            $newArray[$kk]['pele'] = sprintf('%01.2f',$vv['pele']);
//            $newArray[$kk]['tmoney'] = sprintf('%01.2f',$vv['tmoney']);
//        }
        return $newArray;
    }
    function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false, $svr = true) {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if($ssl){
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        if($svr){
            $headers[] = "Content-Type:application/json; charset=utf-8";
        }
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
    if (!function_exists('G_access_token')){
        function G_access_token($appid,$secret){
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $redis = new \Jrk\Redis(config('cache.stores.redis'));
            $token = $redis->get('GZDtoken');
            if($token){
                return $token;
            }else{
                $access_token = httpRequest($url,'GET'); //获取小程序的token
                $data = json_decode($access_token,true);
                dd($data);
                if(isset($data['errcode'])){
                    trace($access_token,'info');
                    return '';
                }else{
                    $redis->set('GZDtoken',$data['access_token'],7100);
                    return $data['access_token'];
                }

            }


        }
    }

    if (!function_exists('access_token')){
        function access_token($appid,$secret){
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $redis = new \Jrk\Redis(config('cache.stores.redis'));
            $token = $redis->get('ZDtoken');
            if($token){
                return $token;
            }else{
                $access_token = httpRequest($url,'GET'); //获取小程序的token
                $data = json_decode($access_token,true);
                if(isset($data['errcode'])){
                    trace($access_token,'info');
                    return '';
                }else{
                    $redis->set('ZDtoken',$data['access_token'],7100);
                    return $data['access_token'];
                }

            }


        }
    }
    function TaxMoney($unit_price,$number,$tax_rate)
    {
        $z_money = $unit_price * $number ;
        $tax_rate = $tax_rate/100 ;
        $data = [];
        $data['tax_money'] =  round($z_money/($tax_rate  + 1) * $tax_rate,2);   //  税金
        $data['money'] = round($z_money - $data['tax_money'] ,2);
        return $data ;
    }
    //组装数据
    function imageInfo($image,$name,$image_id){
        $data = [];
        foreach ($image_id as $key=>$value){
            $data[$key]['id']=$value;
            $data[$key]['name']=$name[$key];
            $data[$key]['url']=$image[$key];
        }
        return $data;
    }
    function taskInfo($text){
        $image_id='';
        $name = '';
        $text = json_decode($text,true);
        foreach ($text as $row){
            $image_id.= $row['id'].',';
            $name.= $row['textname'].',';
        }
        $data['image_id'] = trim($image_id,',');
        $data['name'] = trim($name,',') ;
        return $data;
    }
}